<template>
  <div class="container">
    <div class="header">
      <img
        :src="avatarUrl"
        alt="Avatar"
        @click="selectImage"
        class="avatar"
      />
      <input
        type="file"
        ref="fileInput"
        accept="image/*"
        @change="handleFileChange"
        style="display: none;"
      />
    </div>
    <div class="form-container">
      <form @submit.prevent="submitForm">
        <table class="form-table">
          <tr>
            <td>
              <label>{{ $t('usernameLabel') }}: 
                <span class="display-value">{{ username }}</span>
              </label>
            </td>
          </tr>
          <tr>
            <td>
              <label>{{ $t('identityLabel') }}: 
                <span class="display-value">{{ identity }}</span>
              </label>
            </td>
          </tr>
          <tr>
            <td>
              <label>{{ $t('ageLabel') }}: 
                <span v-if="!isEditing" class="display-value">{{ age }}</span>
                <input v-else type="number" v-model="age" class="edit-input" />
              </label>
            </td>
          </tr>
          <tr>
            <td>
              <label>{{ $t('genderLabel') }}: 
                <span v-if="!isEditing">{{ gender === 'male' ? $t('male') : $t('female') }}</span>
                <div v-else class="gender-options">
                  <label>
                    <input type="radio" v-model="gender" value="male" /> {{ $t('male') }}
                  </label>
                  <label>
                    <input type="radio" v-model="gender" value="female" /> {{ $t('female') }}
                  </label>
                </div>
              </label>
            </td>
          </tr>
          <tr>
            <td>
              <label>{{ $t('phoneLabel') }}: 
                <span v-if="!isEditing" class="display-value">{{ phone }}</span>
                <input v-else type="text" v-model="phone" class="edit-input" />
              </label>
            </td>
          </tr>
          <tr>
            <td>
              <label>{{ $t('conditionLabel') }}: 
                <span v-if="!isEditing" class="display-value">{{ condition }}</span>
                <input v-else type="text" v-model="condition" class="edit-input" />
              </label>
            </td>
          </tr>
        </table>
      </form>
    </div>
    <div class="button-container">
      <button @click="toggleEdit" class="edit-button">
        {{ isEditing ? $t('saveButton') : $t('editButton') }}
      </button>
      <button @click="resetInfo" class="reset-button">{{ $t('resetButton') }}</button>
      <button @click="logout" class="logout-button">{{ $t('logoutButton') }}</button>
    </div>
  </div>
</template>

<script>
import api from '@/api/api';

export default {
  data() {
    return {
      username: '',
      age: 0,
      gender: '',
      identity: '',
      condition: '',
      phone: '', 
      avatarUrl: '',
      galleryImages: [
        require('@/assets/carousel1.jpg'),
        require('@/assets/carousel2.jpg'),
        require('@/assets/carousel3.jpg'),
      ],
      isEditing: false,
      selectedFile: null,
    };
  },
  mounted() {
    this.avatarUrl = localStorage.getItem('avatarUrl') || require('@/assets/logo1.png');
    this.loadUserInfo();
  },
  methods: {
    loadUserInfo() {
      const username = localStorage.getItem('username');
      if (!username) {
        console.error('Username not found in localStorage');
        return;
      }
      api.fetchUserProfile(username).then(response => {
        const user = response.data;
        localStorage.setItem('avatarUrl', user.avatar ? `http://localhost:8081${user.avatar}` : require('@/assets/logo1.png'));
    // 更新页面显示的头像
        this.avatarUrl = localStorage.getItem('avatarUrl');
        this.username = user.username;
        this.age = user.age;
        this.gender = user.gender;
        this.identity = user.identity;
        this.phone = user.phone;
        this.condition = user.illnessinfo;
      }).catch(error => {
        console.error('获取用户信息失败:', error);
        
      });
    },
    toggleEdit() {
      if (!this.isEditing) {
        this.originalData = { ...this.$data };
      } else {
        if (this.hasChanges()) {
          this.submitForm();
        }
      }
      this.isEditing = !this.isEditing;
    },
    hasChanges() {
      const original = this.originalData;
      return (
        this.username !== original.username ||
        this.age !== original.age ||
        this.gender !== original.gender ||
        this.phone !== original.phone ||
        this.identity !== original.identity ||
        this.condition !== original.condition ||
        this.avatarUrl !== original.avatarUrl
      );
    },
    submitForm() {
      const username = localStorage.getItem('username');
      if (!username) {
        console.error('Username not found in localStorage');
        return;
      }

      const formData = new FormData();
      formData.append('username', username);
      formData.append('gender', this.gender);
      formData.append('age', this.age);
      formData.append('phone', this.phone);
      formData.append('illnessinfo', this.condition);

      if (this.selectedFile) {
        formData.append('avatar', this.selectedFile);
      }

      api.updateUserProfile(formData).then(response => {
        console.log('更新成功:', response.data);
        alert('个人信息更新成功！');
        this.isEditing = false;
        this.avatarUrl = response.data.avatar; 
        this.loadUserInfo();
      }).catch(error => {
        console.error('更新失败:', error);
        alert('个人信息更新失败，请稍后再试。');
      });
    },
    selectImage() {
      this.$refs.fileInput.click();
    },
    handleFileChange(event) {
  const file = event.target.files[0];
  if (file && file.type.match('image.*')) {
    // 生成新的文件名，避免重复
    const newFileName = `${Date.now()}_${file.name}`;
    this.selectedFile = new File([file], newFileName, { type: file.type });
    const reader = new FileReader();
    reader.onload = (e) => {
      this.avatarUrl = e.target.result;
    };
    reader.readAsDataURL(this.selectedFile);
  } else {
    alert('请选择图片文件');
  }
},
    resetInfo() {
      if (confirm('确定要重置所有信息吗？')) {
        this.username = this.username;
        this.age = 0;
        this.gender = '';
        this.phone = '';
        this.identity = this.identity;
        this.condition = '';
        this.avatarUrl = '';
        this.isEditing = false;
      }
    },
    logout() {
      if (confirm('确定要退出登录吗？')) {
        localStorage.removeItem('username');
        localStorage.removeItem('identity');
        this.$router.push('/');
      }
    },
  },
};
</script>

<style>
/* 全局样式 */
body {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  background-color: #f5f9fc;
  color: #2d3748;
  line-height: 1.6;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(74, 175, 254, 0.1);
  max-width: 800px;
  margin: 2rem auto;
  border: 1px solid #e3f2fd;
  position: relative;
  overflow: hidden;
}
.container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 5px;
  height: 100%;
  background: linear-gradient(to bottom, #4f8bf9, #2ac9e6);
}

/* 头像样式 */
.header {
  margin: 20px;
  text-align: center;
}
.avatar {
  cursor: pointer;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  border: 2px solid #bbdefb;
  box-shadow: 0 0 10px rgba(26, 115, 232, 0.1);
  transition: all 0.3s;
}
.avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 0 15px rgba(26, 115, 232, 0.2);
}

/* 表单容器样式 */
.form-container {
  background-color: #fff;
  padding: 25px 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  width: 100%;
  max-width: 500px;
  margin: 20px auto;
}

/* 表格样式 */
.form-table {
  width: 100%;
  border-collapse: collapse;
}

td {
  padding: 15px 0;
  vertical-align: middle;
  border-bottom: 1px solid #f0f0f0;
}
td:hover {
  background: rgba(234, 243, 253, 0.5);
}

/* 标签样式 */
label {
  display: flex;
  align-items: center;
  color: #1a73e8;
  font-weight: 500;
  width: 100%;
  font-size: 15px;
}

/* 展示状态 - 内容居中 */
.display-value {
  flex: 1;
  text-align: left;
  font-weight: 400;
  padding-left: 15px;
}

/* 编辑状态 - 保持左对齐 */
.edit-input {
  flex: 1;
  width: 70%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  color: #333;
  font-size: 15px;
  margin-left: 15px;
}


.edit-input:focus {
  border-color: #1a73e8;
  box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
  outline: none;
}


/* 单选按钮组样式 */
.gender-options {
  display: flex;
  gap: 20px;
  justify-content: flex-start;
  margin-left:15px;

}

.gender-options label {
  display: flex;
  align-items: center;
  cursor: pointer;
  width: auto;
  color: #555;
}

/* 按钮容器样式 */
.button-container {
  margin-top: 30px;
  width: 100%;
  max-width: 500px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

button {
  padding: 12px 24px;
  border: none;
  border-radius: 20px;
  color: white;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.edit-button {
  background-color: #2196F3;
}
.reset-button {
  background-color: #2196F3;
}
.logout-button {
  background-color: #2196F3;
}
button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  opacity: 0.9;
}

/* 图片库样式 */
.image-gallery {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  width: 100%;
  max-width: 1200px;
  margin-top: 20px;
  background: #f0f7ff;
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #e3f2fd;
}
.image-item {
  margin: 10px;
}
.gallery-image {
  width: 200px;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(26, 115, 232, 0.1);
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #bbdefb;
}
.gallery-image:hover {
  transform: scale(1.05);
  box-shadow: 0 0 15px rgba(26, 115, 232, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 1.5rem;
    margin: 1rem;
    border-radius: 8px;
  }
  
  .button-container {
    flex-direction: column;
    gap: 10px;
  }
  
  button {
    width: 100%;
  }
  
  .edit-input {
    width: 100%;
  }
  
  .gender-options {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .display-value {
    margin-left: 0;
    text-align: left;
  }
}
</style>